/*
 * @Description:
 * @Version: 0.0.1
 * @Autor: zhj1214
 * @Date: 2021-11-25 10:39:18
 * @LastEditors: zhj1214
 * @LastEditTime: 2021-12-15 16:21:12
 */

import axios from "axios";
import { localStorage } from "@utils/localStorage";
import { STORAGE } from "@utils/constant";
import useMethod from "@store/hock/useMethod";
import VueAxios from "./axios";

const notificationFn = (content, type = "error") => {
  const { $notifi } = window;
  $notifi[type]({
    title: "错误信息",
    content,
    duration: 3000,
  });
};

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL || "",
  timeout: 6000, // 请求超时时间
});

// 异常拦截处理器
const errorHandler = error => {
  if (error.response) {
    const { data } = error.response;
    // 从 localstorage 获取 token
    const token = localStorage.getItem(STORAGE.TOKEN);
    if (error.response.status === 403) {
      notificationFn(data.message);
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notificationFn("Authorization verification failed");
      if (token) {
        const [logout] = useMethod(["Logout"]);
        logout().then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        });
      }
    }
  }
  return Promise.reject(error);
};

// request interceptor
request.interceptors.request.use(config => {
  const token = localStorage.getItem(STORAGE.TOKEN);
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers["Access-Token"] = token;
  }
  return config;
}, errorHandler);

// response interceptor
request.interceptors.response.use(response => {
  return response.data;
}, errorHandler);

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request);
  },
};

export default request;

export { installer as VueAxios, request as axios };
